import React, { useState, useRef, useEffect, useCallback, forwardRef, useImperativeHandle } from 'react';
import './styles.css';

interface SliderVerifyProps {
  width?: number;
  height?: number;
  bgImage?: string;
  puzzleScale?: number;
  onVerify?: (verified: boolean) => void;
  text?: string;
  refreshIcon?: string;
  loadingIcon?: string;
}

export interface SliderVerifyRef {
  reset: () => void;
}

// 预定义一些简单的渐变背景作为验证图片
const backgroundImages = [
  // 蓝色渐变
  '',
  // 紫色渐变
  '',
  // 绿色渐变
  '',
  // 橙色渐变
  '',
  // 彩虹渐变
  ''
];

const getRandomImage = () => {
  return backgroundImages[Math.floor(Math.random() * backgroundImages.length)];
};

const SliderVerify = forwardRef<SliderVerifyRef, SliderVerifyProps>(({
  width = 320,
  height = 160,
  bgImage,
  puzzleScale = 1,
  onVerify = () => {},
  text = "向右滑动完成验证",
  refreshIcon = "刷新",
  loadingIcon = "加载中"
}, ref) => {
  const [isLoading, setIsLoading] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const [startX, setStartX] = useState(0);
  const [offsetX, setOffsetX] = useState(0);
  const [puzzleLeft, setPuzzleLeft] = useState(0);
  const [verified, setVerified] = useState(false);
  const [currentBgImage, setCurrentBgImage] = useState('');

  const sliderRef = useRef<HTMLDivElement>(null);
  const puzzleRef = useRef<HTMLDivElement>(null);
  const bgImageRef = useRef<HTMLImageElement>(null);

  const generateRandomPosition = useCallback(() => {
    const min = width * 0.1;
    const max = width * 0.8;
    return Math.floor(Math.random() * (max - min) + min);
  }, [width]);

  const loadNewImage = useCallback(() => {
    setIsLoading(true);
    const newImage = bgImage || getRandomImage();
    setCurrentBgImage(newImage);
    // 由于使用base64图片，加载应该是即时的
    setIsLoading(false);
  }, [bgImage]);

  const reset = useCallback(() => {
    setIsDragging(false);
    setOffsetX(0);
    setVerified(false);
    loadNewImage();
    const newPuzzleLeft = generateRandomPosition();
    setPuzzleLeft(newPuzzleLeft);
  }, [generateRandomPosition, loadNewImage]);

  useImperativeHandle(ref, () => ({
    reset
  }));

  useEffect(() => {
    reset();
  }, [reset]);

  const handleMouseDown = (e: React.MouseEvent | React.TouchEvent) => {
    if (verified || isLoading) return;
    
    setIsDragging(true);
    if ('touches' in e) {
      setStartX(e.touches[0].clientX);
    } else {
      setStartX(e.clientX);
    }
  };

  const handleMouseMove = (e: React.MouseEvent | React.TouchEvent) => {
    if (!isDragging || verified || isLoading) return;

    let currentX;
    if ('touches' in e) {
      currentX = e.touches[0].clientX;
    } else {
      currentX = e.clientX;
    }

    const diff = currentX - startX;
    const newOffsetX = Math.max(0, Math.min(diff, width - 40));
    setOffsetX(newOffsetX);

    // 验证
    const tolerance = 5;
    if (Math.abs(newOffsetX - puzzleLeft) < tolerance) {
      setVerified(true);
      setIsDragging(false);
      onVerify(true);
    }
  };

  const handleMouseUp = () => {
    if (!isDragging || verified || isLoading) return;

    setIsDragging(false);
    if (!verified) {
      setOffsetX(0);
      onVerify(false);
    }
  };

  useEffect(() => {
    const handleGlobalMouseUp = () => handleMouseUp();
    document.addEventListener('mouseup', handleGlobalMouseUp);
    document.addEventListener('touchend', handleGlobalMouseUp);

    return () => {
      document.removeEventListener('mouseup', handleGlobalMouseUp);
      document.removeEventListener('touchend', handleGlobalMouseUp);
    };
  }, [isDragging, verified]);

  return (
    <div className="slider-verify-container" style={{ width }}>
      <div className="slider-verify-image-container" style={{ width, height }}>
        {isLoading && (
          <div className="slider-verify-loading">
            {loadingIcon}
          </div>
        )}
        <img
          ref={bgImageRef}
          src={currentBgImage}
          alt="验证背景"
          className={`slider-verify-bg ${isLoading ? 'loading' : ''}`}
          style={{ width, height }}
        />
        <div
          ref={puzzleRef}
          className="slider-verify-puzzle"
          style={{
            left: `${offsetX}px`,
            top: '50%',
            transform: 'translateY(-50%)',
            width: `${40 * puzzleScale}px`,
            height: `${40 * puzzleScale}px`,
            backgroundColor: verified ? '#52c41a' : '#1677ff'
          }}
        />
        <div
          className="slider-verify-puzzle-shadow"
          style={{
            left: `${puzzleLeft}px`,
            top: '50%',
            transform: 'translateY(-50%)',
            width: `${40 * puzzleScale}px`,
            height: `${40 * puzzleScale}px`
          }}
        />
      </div>
      <div
        ref={sliderRef}
        className={`slider-verify-slider ${isDragging ? 'dragging' : ''} ${verified ? 'verified' : ''}`}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onTouchStart={handleMouseDown}
        onTouchMove={handleMouseMove}
      >
        <div
          className="slider-verify-slider-mask"
          style={{ width: `${offsetX + 40}px` }}
        />
        <div
          className="slider-verify-slider-button"
          style={{ left: `${offsetX}px` }}
        >
          {isLoading ? loadingIcon : '→'}
        </div>
        <div className="slider-verify-slider-text">
          {verified ? '验证成功' : text}
        </div>
        {verified && (
          <div
            className="slider-verify-refresh"
            onClick={reset}
          >
            {refreshIcon}
          </div>
        )}
      </div>
    </div>
  );
});

export default SliderVerify; 